import urllib.parse
import urllib.request
import json
#APIID：C35731291
#APIKEY：735f0b6c8d4afe1b5e69d73c8a97bb71

#接口地址
class Sms:
    url = 'http://106.ihuyi.com/webservice/sms.php?method=Submit'
    def sent(self, mobile, code):
        #定义请求的数据
        values = {
            'account': 'C35731291',
            'password': '735f0b6c8d4afe1b5e69d73c8a97bb71',
            'mobile': f'{mobile}',
            # 'content': f'欢迎使用【夕夕商城】：您的验证码为{code}，【夕夕商城】提醒您请不要把验证码泄露给其他人。---张瑞阳',
            'content' : f'您的验证码是：{code}。请不要把验证码泄露给其他人。',
            'format': 'json',
        }

        #将数据进行编码
        data = urllib.parse.urlencode(values).encode(encoding='UTF8')

        #发起请求
        req = urllib.request.Request(self.url, data)
        response = urllib.request.urlopen(req)
        res = response.read()

        #打印结果
        resp = json.loads(res.decode("utf8"))
        resp_code = resp.get('code')
        print(resp_code)
        smsid = resp.get('smsid')
        if resp_code == 4051:
            raise ('Error: the api of code is limit')
        elif resp_code == 406:
            raise ('Error: the api of code error/n the mobile is wrong')
        elif resp_code != 2:
            raise (f'Error: the api of code error/n.  The api response_code is {resp_code}, pleace get to https://www.ihuyi.com/api/sms.html find the problems')
        return resp_code, smsid

if __name__ == '__main__':
    sms = Sms()
    sms.sent('18836096773', '5674')